﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using BEPUphysics.Entities;
using Microsoft.Xna.Framework;

namespace Asplode.Renderer
{
    public class AsplodeRenderer
    {
        public List<RenderPair> models = new List<RenderPair>();
        public Game game;

        public Queue<RendererExplosion> explosions = new Queue<RendererExplosion>();

        public AsplodeRenderer(Game game1){
            game = game1;
        }

        public void Draw()
        {
            foreach (RenderPair renderpair in models)
            {
                Matrix worldMatrix = renderpair.transform * renderpair.Entity.internalWorldTransform;

                renderpair.Model.CopyAbsoluteBoneTransformsTo(renderpair.boneTransforms);
                
                foreach (ModelMesh mesh in renderpair.Model.Meshes)
                {
                    foreach (BasicEffect effect in mesh.Effects)
                    {
                        effect.World = renderpair.boneTransforms[mesh.ParentBone.Index] * worldMatrix;
                        effect.View = game.Map.Camera.CameraView;
                        effect.Projection = game.Map.CameraProjection;
                        effect.DiffuseColor = Color.Gray.ToVector3();
                        effect.Alpha = 1.0f;
                    }
                    mesh.Draw();
                }
            }

            DateTime cutoffTime = DateTime.Now.AddSeconds(-1);

            // Remove old explosions.
            while (explosions.Count > 0 && explosions.Peek().startTime < cutoffTime)
            {
                explosions.Dequeue();
            }

            foreach (RendererExplosion explosion in explosions)
            {
                Matrix worldMatrix = explosion.transform;

                explosion.Model.CopyAbsoluteBoneTransformsTo(explosion.boneTransforms);

                // Make alpha go from 0.5 to 0 in 1 second.
                float alpha = ((explosion.startTime - cutoffTime).Milliseconds / 2) / 1000.0f;

                if (alpha > 0.0f)
                {
                    foreach (ModelMesh mesh in explosion.Model.Meshes)
                    {
                        foreach (BasicEffect effect in mesh.Effects)
                        {
                            effect.World = explosion.boneTransforms[mesh.ParentBone.Index] * worldMatrix;
                            effect.View = game.Map.Camera.CameraView;
                            effect.Projection = game.Map.CameraProjection;
                            effect.DiffuseColor = Color.Orange.ToVector3();
                            effect.Alpha = alpha;
                        }
                        mesh.Draw();
                    }
                }
            }
        }
    }    
}
